#include "xconfig_handle.h"
#include <xplatform/XTools.h>
#include <xplatform/protobuf/xmsg_com.pb.h>
#include "config_dao.h"
#include <string>
using namespace std;
XConfigServerHandle::XConfigServerHandle()
{
}

XConfigServerHandle::~XConfigServerHandle()
{
    XCOM_LOG_INFO("XConfigServerHandle::~XConfigServerHandle()");
}
void XConfigServerHandle::SaveConfig(xmsg::XMsgHead *head, XMsg *msg)
{
    if(msg->type==xmsg::MSG_SAVE_CONFIG_REQ){
        xmsg::XConfig config;
        config.ParseFromArray(msg->data,msg->size);
        xmsg::XMessageRes res;
        if(!ConfigDao::Get()->SaveConfig(&config)){
            XCOM_LOG_DEBUG("SaveConfig failed");
            res.set_return_(xmsg::XMessageRes::FAIL);
            res.set_msg("SaveConfig to mysql failed!");
            SendMsg(xmsg::MSG_SAVE_CONFIG_RES,&res);
            return ;
        }
        res.set_return_(xmsg::XMessageRes::SUCCESS);
        res.set_msg("SaveConfig success");
        SendMsg(xmsg::MSG_SAVE_CONFIG_RES,&res);
        XCOM_LOG_DEBUG("SaveConfig success");
    }
}

void XConfigServerHandle::LoadConfig(xmsg::XMsgHead *head, XMsg *msg)
{
    xmsg::XLoadConfigReq configReq;
    if(!configReq.ParseFromArray(msg->data,msg->size)){
        XCOM_LOG_DEBUG("configReq.ParseFromArray failed");
        return;
    }
    //
    string ip = configReq.service_ip();
    if(ip.empty()){
        XCOM_LOG_DEBUG("ip is null");
        ip=client_ip();
    }
    xmsg::XConfig config=ConfigDao::Get()->LoadConfig(ip.c_str(),configReq.service_port());
    SendMsg(xmsg::MSG_LOAD_CONFIG_RES,&config);
}

void XConfigServerHandle::LoadAllConfig(xmsg::XMsgHead *head, XMsg *msg)
{
    xmsg::XLoadAllConfigReq configReq;
    if(!configReq.ParseFromArray(msg->data,msg->size)){
        XCOM_LOG_DEBUG("configReq.ParseFromArray failed");
    }
    xmsg::XConfigList configList=ConfigDao::Get()->LoadAllConfig(configReq.page(),configReq.page_count());
    SendMsg(xmsg::MSG_LOAD_ALL_CONFIG_RES,&configList);
}

void XConfigServerHandle::DelConfig(xmsg::XMsgHead *head, XMsg *msg)
{
    xmsg::XLoadConfigReq req;
    xmsg::XMessageRes res;
    if(!req.ParseFromArray(msg->data,msg->recv_size)){
        res.set_return_(xmsg::XMessageRes::FAIL);
        res.set_msg("ParseFromArray fail!");
        SendMsg(xmsg::MSG_DEL_CONFIG_RES,&res);
        return;
    }
    if(!ConfigDao::Get()->DeleteConfig(req.service_ip().c_str(),req.service_port())){
        res.set_return_(xmsg::XMessageRes::FAIL);
        res.set_msg("ConfigDao::Get()->DeleteConfig fail!");
        SendMsg(xmsg::MSG_DEL_CONFIG_RES,&res);
        return;
    }
    res.set_return_(xmsg::XMessageRes::SUCCESS);
    res.set_msg("ok!");
    SendMsg(xmsg::MSG_DEL_CONFIG_RES,&res);
}
